const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join('-')
}

//防止用户多次点击，重复触发请求
function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }

  let _lastTime = null

  // 返回新的函数
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}

//把obj对象里的值覆盖到newobj里面
function deepCopy(newobj, obj) {
  if (typeof obj != 'object') {
    return obj;
  }
  for (var attr in obj) {
    var a = {};
    if (newobj[attr]) {
      a = newobj[attr];
    }
    newobj[attr] = deepCopy(a, obj[attr]);
  }
  return newobj;
}


function navigateTo(url) {
  if (getCurrentPages().length >= 10) {
    wx.redirectTo({
      url: url,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  } else {
    wx.navigateTo({
      url: url,
    })
  }
}


module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  throttle: throttle,
  deepCopy: deepCopy,
  navigateTo: navigateTo,
  api: "http://userapi.zhikaisoft.com/"
  // api: "https://chattest.metromall.cn/metromall/"
  // api: "https://welfareapitest.metromall.cn/"
}
